<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
include('../../include/dbFunctions.php');
include ("../../include/image_slider.php");
include ("../../include/function.php");


//GET school ID from URL you just clicked
    if (isset($_GET['id'])) {
        $event_id = $_GET['id'];
        $_SESSION['event_id'] = $event_id;
    } elseif (isset($_SESSION['event_id'])) {
        $event_id = $_SESSION['event_id'];
    }
//Make $id become GLOBAL for passing to next page for \further usage
if (isset($_SESSION['school_id'])) {
    if (isset($_POST['edit_event'])) {

        $session = "SELECT * FROM session WHERE event_id = $event_id";
        $session = executeSelectQuery($session);

        $program = "SELECT e.program_id, p.program_lesson_duration
                FROM event e, program p
                WHERE e.program_id = p.program_id
                AND e.event_id = $event_id
               ";
        $program = executeSelectQuery($program);
        $program_duration = $program[0]['program_lesson_duration'];

        $no_session = $_POST['no_session'];

        $date_array = array();
        $time_array = array();
        $end_time_array = array();

        for ($i = 0; $i < $no_session; $i++) {
            $date_array[] = $_POST['date' . $i . ''];
            $time_array[] = $_POST['time' . $i . ''];
            $end_time_array[] = $_POST['end_time' . $i . ''];
        }


        $msg = '';
        $duration = array();
        $true = 0;

        for ($i = 0; $i < count($time_array); $i++) {
            $new_time = explode(":", $time_array[$i]);
            $new_time = $new_time[0] * 60 + $new_time[1];

            $new_end_time = explode(":", $end_time_array[$i]);
            $new_end_time = $new_end_time[0] * 60 + $new_end_time[1];
            $duration[] = $new_end_time - $new_time;
            if ($new_end_time < $new_time) {
                $true = $true + 1;
                $num = $i + 1;
                $msg.= "End time is earlier than start time at session number $num! <br>";
            }
        }

        $total = 0;
        $true1 = 0;



        if ($true == 0) {
            for ($i = 0; $i < count($duration); $i++) {
                $total = $total + $duration[$i];
            }
            $total_hour = $total / 60;
            $hour = floor($total_hour);
            $minute = $total % 60;

            $require = explode(":", $program_duration);
            $require = $require[0] * 60 + $require[1];
            $original = $program_duration;

            if ($require > $total) {
                $true1 = $true1 + 1;
                $msg.= "Your sessions total duration is " . $hour . ":" . $minute . ". However, the total duration of this course is " . $original . ".<br>";
            }
        }

        $array = array();
        $new_array = array();
        $error = 0;
        $error1 = 0;
        for ($i = 0; $i < count($date_array); $i++) {
            $array[] = $date_array[$i] . '-' . $time_array[$i];
        }
        for ($t = 0; $t < count($array); $t++) {
            for ($j = 0; $j < count($array); $j++) {
                if ($t != $j) {
                    if ($array[$t] == $array[$j]) {
                        $error = $error + 1;
                    }
                }
            }
        }
       
        if ($error != 0) {
            $msg.="There are sessions that have the same day and start time.<br>";
        }

        $munite1_array = array();
        $munite2_array = array();
        for ($i = 0; $i < count($time_array); $i++) {
            $minute1 = explode(":", $time_array[$i]);
            $minute1 = $minute1[0] * 60 + $minute1[1];
            $munite1_array[] = $minute1;

            $minute2 = explode(":", $end_time_array[$i]);
            $minute2 = $minute2[0] * 60 + $minute2[1];
            $munite2_array[] = $minute2;
        }

        for ($i = 0; $i < count($date_array); $i++) {
            $new_array[] = $date_array[$i] . '-' . $munite1_array[$i] . '-' . $munite2_array[$i];
        }
        for ($i = 0; $i < count($new_array); $i++) {
            for ($t = 0; $t < count($new_array); $t++) {
                if ($i != $t) {
                    $com1 = explode("-", $new_array[$i]);
                    $com2 = explode("-", $new_array[$t]);
                    if ($com1[0] == $com2[0] && (($com2[1] > $com1[1] && $com2[1] < $com1[2]) || ($com2[2] > $com1[1] && $com2[2] < $com1[2] ) )) {
                        $error1 = $error1 + 1;
                    }
                }
            }
        }
        
        if ($error1 != 0) {
            $msg.= "There are overlap sessions<br>";
        }


        if ($true != 0) {
            $msg.= "Please go back and modify your sessions.<br> <input type='button' value='&nbsp' class='form-back' onclick='history.go(-1)'/>";
        }
        if ($true == 0 && $true1 != 0) {
            $msg.= "Please go back and modify your sessions.<br> <input type='button' value='&nbsp' class='form-back' onclick='history.go(-1)'/>";
        }
        if ($true == 0 && $true1 == 0 && $error != 0) {
            $msg.= "Please go back and modify your sessions.<br> <input type='button' value='&nbsp' class='form-back' onclick='history.go(-1)'/>";
        }
        if ($true == 0 && $true1 == 0 && $error == 0 && $error1 != 0) {
            $msg.= "Please go back and modify your sessions.<br> <input type='button' value='&nbsp' class='form-back' onclick='history.go(-1)'/>";
        }



        if ($true == 0 && $true1 == 0 && $error == 0 && $error1 == 0) {

            for ($i = 0; $i < count($date_array); $i++) {

                $date = explode("/", $date_array[$i]);

                $final_date = "$date[2]-$date[0]-$date[1]";

                $update_session = "UPDATE session SET session_date = '$final_date',
                                              session_time = '$time_array[$i]',
                                              session_end_time = '$end_time_array[$i]'
                                          WHERE session_id = " . $session[$i]['session_id'] . "   
                                    ";
                $update_session = executeQuery($update_session);
            }
        }
    }

    /*
      if (isset($_POST['add_class'])) {

      $class_name = htmlspecialchars($_POST['class_name'], ENT_QUOTES);
      $no_student = $_POST['no_student'];


      if (isset($_FILES['file'])) {

      $filename = strtolower($_FILES['file']['name']);
      $exts = explode(".", $_FILES['file']['name']);
      $n = count($exts) - 1;
      $ext = $exts[$n];

      $ran = rand();
      $ran2 = $ran . ".";
      $target = "../../admin/upload/";
      $target = $target . $ran2 . $ext;

      move_uploaded_file($_FILES['file']['tmp_name'], $target);
      $volunteer_cv = $ran2 . $ext;

      /*$target_path = "../../admin/upload/";
      $volunteer_cv = $_FILES['file']['name'];
      $target_path = $target_path . basename($_FILES['file']['name']);
      move_uploaded_file($_FILES['file']['tmp_name'], $target_path);

      }
      $insert_class = "INSERT INTO class(class_name, class_no_student, class_student_list, event_id)
      VALUES('$class_name', '$no_student', '$volunteer_cv', $event_id)";

      $insert_class = executeQuery($insert_class);
      }
     */
    if (isset($_POST['edit_class'])) {

        $no_class = $_POST['no_class'];

        $class_name = array();
        $no_student = array();

        $class_level = $_POST['class_level'];

        $insert_level = "UPDATE event SET event_class_level = '$class_level' WHERE event_id = $event_id";
        $insert_level = executeSelectQuery($insert_level);


        for ($i = 0; $i < $no_class; $i++) {

            $class_name[] = htmlspecialchars($_POST['class_name' . $i . ''], ENT_QUOTES);
            $no_student[] = $_POST['no_student' . $i . ''];


            $class = "SELECT * FROM class WHERE event_id = $event_id";
            $class = executeSelectQuery($class);
        }

        for ($i = 0; $i < count($class_name); $i++) {

            if (isset($_FILES['file' . $i . '']) && $_FILES['file' . $i . '']['name'] != '') {

                if ($class[$i]['class_student_list'] == '') {

                    $filename = strtolower($_FILES['file' . $i . '']['name']);
                    $exts = explode(".", $_FILES['file' . $i . '']['name']);
                    $n = count($exts) - 1;
                    $ext = $exts[$n];

                    $ran = rand();
                    $ran2 = $ran . ".";
                    $target = "../../admin/upload/";
                    $target = $target . $ran2 . $ext;

                    move_uploaded_file($_FILES['file' . $i . '']['tmp_name'], $target);
                    $volunteer_cv = $ran2 . $ext;

                    /* $target_path = "../../admin/upload/";
                      $volunteer_cv = $_FILES['file' . $i . '']['name'];
                      $target_path = $target_path . basename($_FILES['file' . $i . '']['name']);
                      move_uploaded_file($_FILES['file' . $i . '']['tmp_name'], $target_path);

                     */
                } else {

                    $tmpfile = "../../admin/upload/" . $class[$i]['class_student_list'] . "";
                    unlink($tmpfile);

                    $filename = strtolower($_FILES['file' . $i . '']['name']);
                    $exts = explode(".", $_FILES['file' . $i . '']['name']);
                    $n = count($exts) - 1;
                    $ext = $exts[$n];

                    $ran = rand();
                    $ran2 = $ran . ".";
                    $target = "../../admin/upload/";
                    $target = $target . $ran2 . $ext;

                    move_uploaded_file($_FILES['file' . $i . '']['tmp_name'], $target);
                    $volunteer_cv = $ran2 . $ext;

                    /*   $target_path = "../../admin/upload/";
                      $volunteer_cv = $_FILES['file' . $i . '']['name'];
                      $target_path = $target_path . basename($_FILES['file' . $i . '']['name']);
                      move_uploaded_file($_FILES['file' . $i . '']['tmp_name'], $target_path);
                     * 
                     */
                }

                $update_class = "UPDATE class SET class_name = '$class_name[$i]',
                                               class_no_student = '$no_student[$i]', 
                                               class_student_list = '$volunteer_cv'
                                               
                                               WHERE class_id = " . $class[$i]['class_id'] . "
                                 ";

                $update_class = executeQuery($update_class);
            } else {
                $update_class1 = "UPDATE class SET class_name = '$class_name[$i]',
                                               class_no_student = '$no_student[$i]',
                                               
                                               WHERE class_id = " . $class[$i]['class_id'] . "
                                 ";

                $update_class1 = executeQuery($update_class1);
            }
        }
    }


//Select event and program details
    $sQuery = "SELECT e.event_id, e.event_name, e.contact_id, e.program_id,e.event_status, e.event_class_level, p.program_name, p.program_lesson_duration
           FROM  event e,program p
           WHERE p.program_id = e.program_id
           AND event_id = $event_id";
    $event = executeSelectQuery($sQuery);

// Select school details
    $school = "SELECT s.school_name, s.school_address, s.school_postal
            FROM school s, contact_school c, event e
            WHERE c.contact_school_id = e.contact_id
            AND s.school_id = c.school_id
            AND e.event_id = $event_id
           ";
    $school = executeSelectQuery($school);

// Select session
    $session = "SELECT * FROM session WHERE event_id = $event_id";
    $session = executeSelectQuery($session);

// Select class
    $class_array = "SELECT * FROM class WHERE event_id = $event_id";
    $class_array = executeSelectQuery($class_array);

// select program
    $program = "SELECT * FROM program p, event e WHERE p.program_id = e.program_id AND e.event_id = $event_id";
    $program = executeSelectQuery($program);
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Junior Achievement Singapore</title>
        <link href="../../media/css/styles.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" language="javascript" src="../../media/js/jquery/jquery-1.6.1.min.js"></script>
        <script type="text/javascript" src="../../media/js/jquery/jqdialog.min.js"></script>
        <script type="text/javascript" src="../../media/js/jqueryUI/jquery.ui.dialog.js"></script>

        <script type="text/javascript" src="../../media/js/jquery/image_slider.js"></script>
        <script src="../../media/js/jquery/custom_jquery.js" type="text/javascript"></script>

        <link type="text/css" href="../../media/css/dataTable.css" rel="stylesheet" />
        <script type="text/javascript" language="javascript" src="../../media/js/jquery/dataTable.js"></script>
        <script type="text/javascript" language="javascript" charset="utf-8">
            $(document).ready(function(){
                   
                $('#eventtable1').dataTable( {
                    "sPaginationType": "full_numbers"
                } );
                $('#eventtable2').dataTable( {
                    "sPaginationType": "full_numbers"
                } );
            });
        </script>
    </head>
    <body>
        <script>
            var timeout    = 500;
            var closetimer = 0;
            var ddmenuitem = 0;

            function jsddm_open()
            {  jsddm_canceltimer();
                jsddm_close();
                ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

            function jsddm_close()
            {  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

            function jsddm_timer()
            {  closetimer = window.setTimeout(jsddm_close, timeout);}

            function jsddm_canceltimer()
            {  if(closetimer)
                {  window.clearTimeout(closetimer);
                    closetimer = null;}}

            $(document).ready(function()
            {  $('#navigation > li').bind('mouseover', jsddm_open)
                $('#navigation > li').bind('mouseout',  jsddm_timer)});

            document.onclick = jsddm_close;

        </script>
        <div id="container"><!--CONTAINER STARTS-->
            <div id="navigation">
                <li><a href="../../include/home/homepage.php">HOME</a></li>
                <li><a href="../../include/home/contact.php">CONTACT</a></li>
                <li><a href="http://ja.org.sg/">ABOUT JA SINGAPORE</a></li>
                <li><a href="http://jascheduling.lefora.com/">FEEDBACK</a></li>
                <li><a href="../../guide/guide_menu.php">HELP</a></li>

            </div>
            <div id="title"><!--TITLE STARTS-->
            </div><!--TITLE ENDS-->
            <div id="featured"><!--FEATURED AREA STARTS-->

                <div class="featured-image"><!--FEATURED IMAGE STARTS-->
                    <img alt="Featured Image" src="../../media/images/featured_image.png"></img>
                </div><!--FEATURED IMAGE ENDS-->
                <div class="featured-text"><!--FEATURED TEXT STARTS-->

                    <h2>Welcome to JA Singapore</h2>
                    <p>Junior Achievement programs help prepare young people for the real world by showing them how to generate wealth and effectively manage it, how to create jobs which make their communities more robust, and how to apply entrepreneurial thinking to the workplace. <a href="http://www.jaworldwide.org/">Read More... </a></p>
                </div><!--FEATURED TEXT ENDS-->
            </div><!--FEATURED AREA ENDS-->
            <?php
            custom_login();
            ?>
            <div id="left-content"><!--RIGHT CONTENT STARTS-->
                <div class="left-top"><!--RIGHT CONTENT BOX TOP-->
                </div><!--RIGHT CONTENT BOX TOP ENDS-->
                <div class="left-middle"><!--RIGHT CONTENT BOX MIDDLE-->
                    <?php
                    if (!isset($_SESSION['school_id'])) {
                        echo "<br/><br/><br/><br/><br/><center><h3>You don't have permission to view this page<h3><br/>
                      Please login to access the page.</center><br/><br/><br/><br/><br/><br/><br/><br/>";
                    } else {
                        if ((isset($true) && isset($true1) && isset($error) && isset($error1)) && ($true != 0 || $true1 != 0 || $error != 0 || $error1 != 0)) {
                            echo "<br><br><br>" . $msg;
                        } else {
                            ?>
                            <h3>Course Details</h3>
                            <table id="ongoing_events" class="tabledetail">
                                <tr>
                                    <th class="tabledetailth">Course Name: </th>
                                    <td><?php echo $event[0]['event_name'] ?></td>
                                </tr>
                                <tr>
                                    <th class="tabledetailth">Course Status: </th>
                                    <td><?php echo $event[0]['event_status'] ?></td>
                                </tr>
                                <tr>
                                    <th class="tabledetailth">Program Name: </th>
                                    <td><?php echo $event[0]['program_name'] ?></td>
                                </tr>
                                <tr>
                                    <th class="tabledetailth">School Name: </th>
                                    <td><?php echo $school[0]['school_name'] ?></td>
                                </tr>
                                <tr>
                                    <th class="tabledetailth">School Address: </th>
                                    <td><?php echo $school[0]['school_address'] ?></td>
                                </tr>
                                <tr>
                                    <th class="tabledetailth">School Postal Code: </th>
                                    <td><?php echo $school[0]['school_postal'] ?></td>
                                </tr>    
                            </table>


                            <br/><br/><br/>
                            <h3>Sessions: </h3>   
                            <table  cellpadding="0" cellspacing="0" border="0" class="display" id="eventtable1">
                                <thead>
                                    <tr>
                                        <th>No.</th>
                                        <th>Date</th>
                                        <th>Start time</th>
                                        <th>End time</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    for ($i = 0; $i < count($session); $i++) {
                                        ?>
                                        <tr>
                                            <td><?php echo $i + 1; ?></td>
                                            <td><?php echo $session[$i]['session_date'] ?></td>
                                            <td><?php echo $session[$i]['session_time'] ?></td>
                                            <td><?php echo $session[$i]['session_end_time'] ?></td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                </tbody>
                            </table > 
                            <br/><br/>
                                    <?php
                                    if ($event[0]['event_status'] == 'requested') {
                                        ?>
                                        <input type='button' value='&nbsp' class="form-edit" onClick="window.location.href='editSession.php'"/>
                                        <?php
                                    }
                                    ?>
                                    <br/><br/><br/><br/>
                                                    <h3>Classes:</h3>
                                                    Class level: <?php echo $event[0]['event_class_level'] ?><br/>
                                                        <table cellpadding="0" cellspacing="0" border="0" class="display" id="eventtable2">
                                                            <thead>
                                                                <tr>
                                                                    <th>No.</th>
                                                                    <th>Class Name</th>
                                                                    <th>No. Student</th>
                                                                    <th>Student File</th>
                                                                    <th> Volunteers </th>

                                                                </tr> 
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                $class_array2 = array();
                                                                for ($i = 0; $i < count($class_array); $i++) {
                                                                    $no = $i + 1;
                                                                    $cid = $class_array[$i]['class_id'];
                                                                    $name = $class_array[$i]['class_name'];
                                                                    $no_student = $class_array[$i]['class_no_student'];
                                                                    $file = $class_array[$i]['class_student_list'];
                                                                    $classid = $class_array[$i]['class_id'];
                                                                    echo "<tr>";
                                                                    echo "<td>$no</td>";
                                                                    echo "<td>$name</td>";
                                                                    echo "<td>$no_student</td>";
                                                                    if ($file != "") {
                                                                        echo "<td><a target='_blank' href='../../admin/upload/$file'>Download</a></td>";
                                                                    } else {
                                                                        echo "<td>No file</td>";
                                                                    }
                                                                    // get volunteer data
                                                                    $query2 = "SELECT v.volunteer_surname, v.volunteer_firstname, v.volunteer_id
                                                                                    FROM trainer t, volunteer v
                                                                                    WHERE t.volunteer_id = v.volunteer_id
                                                                                    AND t.trainer_status= 'confirmed'
                                                                                    AND t.event_id=$event_id
                                                                                    AND t.class_id =$cid";
                                                                    $trainer_array = executeSelectQuery($query2);

                                                                    for ($j = 0; $j < count($trainer_array); $j++) {
                                                                        $trainer_array[$j]['volunteer_name'] = $trainer_array[$j]['volunteer_firstname'] . " " . $trainer_array[$j]['volunteer_surname'];
                                                                    }
                                                                    echo "<td>";
                                                                    for ($t = 0; $t < count($trainer_array); $t++) {

                                                                        $trainer_name = "<a href = ../../volunteer/volunteer_detail/volunteerDetail.php?id=" . $trainer_array[$t]['volunteer_id'] . ">" . $trainer_array[$t]['volunteer_name'] . "</a>";
                                                                        echo $trainer_name . "<br>";
                                                                    }
                                                                    echo "</td>";

                                                                    echo "</tr>";
                                                                }
                                                                ?>
                                                            </tbody>
                                                        </table>
                                                        <br/><br/>
                                                                <?php
                                                                if ($event[0]['event_status'] == 'requested') {
                                                                    ?>
                                                                    <input type='button' value='&nbsp' class="form-edit" onClick="window.location.href='editClass.php'"/>

                                                                    <?php
                                                                }
                                                                ?>
                                                                <br/><br/>

                                                                                    <?php
                                                                                    if ($event[0]['event_status'] != 'requested') {
                                                                                        ?>
                                                                                        <input type='button' value='&nbsp' onClick="window.location.href='viewRepresentativeEvent.php'" class="form-back"/>
                                                                                        <?php
                                                                                    }
                                                                                    ?>

                                                                                    <?php
                                                                                    if ($event[0]['event_status'] == 'requested') {
                                                                                        ?>

                                                                                        <table>
                                                                                            <tr>
                                                                                                <td><input type='button' value='&nbsp' onClick="window.location.href='viewRepresentativeEvent.php'" class="form-back"/></td>

                                                                                                <td><form action="schoolRemoveEvent.php">
                                                                                                        <button class="form-remove" onClick="if (confirm('Are you sure you want to remove?')) commentDelete(1); return false">Remove</button>
                                                                                                    </form>
                                                                                                </td>
                                                                                            </tr>
                                                                                        </table>

                                                                                        <?php
                                                                                    } else {
                                                                                        echo "<p class='pmain'>Sorry this Course cannot be edited or deleted. Please contact <a href ='mailto:hauyee.ng@ja.org'><font color='#0000FF'>JA Singapore Director Ms. Ng Hau Yee </font></a> for more details.</p>";
                                                                                    }
                                                                                    ?>

                                                                                    <?php
                                                                                }
                                                                            }
                                                                            ?>
                                                                            </div><!--RIGHT CONTENT BOX MIDDLE ENDS-->
                                                                            <div class="left-bottom"><!--RIGHT CONTENT BOX BOTTOM-->
                                                                            </div><!--RIGHT CONTENT BOX BOTTOM ENDS-->
                                                                            </div><!--RIGHT CONTENT ENDS-->
                                                                            </div><!--CONTAINER ENDS-->
                                                                            <div id="footer"><!--FOOTER STARTS-->
                                                                                <p>Copyright &copy; Junior Achievement Singapore | All Rights Reserved</p>
                                                                            </div><!--FOOTER ENDS-->
                                                                            </body>
                                                                            </html>
